###**********************************************###
### Unique Keychain Python Code                  ###
### ECE 387, Miami University, Spring 2013       ###
### Created By: Andrew Heldt, Lee Mondini and    ###
### Shiloh Womack                                ###   
###**********************************************###
import serial, sys, feedparser, pprint, time, imaplib

#Settings - Change these to match your account details
USERNAME="387keychain"
PASSWORD="keychain2013"
SERIALPORT = 'COM4'
NO_MAIL = b'm'
YES_MAIL = b'n'

# Set up COM4 - Our arduino port
try:
	ser = serial.Serial(SERIALPORT, 9600)
except serial.SerialException:
	print ("no device connected - exiting")
	sys.exit()

# Need to figure out how to get this to keep running forever
for num in range(0,10):
        obj = imaplib.IMAP4_SSL('imap.gmail.com','993')
        obj.login(USERNAME,PASSWORD)
        obj.select()

        newmails = len(obj.search(None, 'UnSeen')[1][0].split())

        time.sleep(5)

        # Output data to serial port
        if newmails > 0:
                ser.write(YES_MAIL)
        else: 
                ser.write(NO_MAIL)
        #print data to terminal

# Close serial port
ser.close()
 
